<template>
	<view class="message">
		<view class="message_list">
			<view class="message_list_item" v-for="(msg, index) in messages.data">
				<view class="message_content">
					<view class="label">[{{ i18n(parseType(msg.type)) }}]</view>
					<custom-msg-to-component :item="{ message: msg.content, data: msg.aside }"></custom-msg-to-component>
				</view>
				<view class="message_time">{{ parseDate(msg.time) }}</view>
			</view>
		</view>
		<custom-gotop v-show="isShowGoTop"></custom-gotop>
	</view>
</template>

<script>
export default {
	data() {
		return {
			isShowGoTop: false,
			messages: {
				data: []
			},
			pn: 0,
			loading: false
		};
	},
	onShow() {
		this.boolLogin()
	},
	onLoad() {
		let that = this;
		this.boolLogin().then(() => {
			that.getMessageData(this.pn);
		});
	},
	onPullDownRefresh() {
		let that = this;
		this.boolLogin().then(() => {
			that.getMessageData(that.pn).finally(() => {
				uni.stopPullDownRefresh();
			});
		});
	},
	onReachBottom() {
		let that = this;
		this.boolLogin().then(() => {
			if (!that.loading) {
				that.loading = true;
				that.getMessageData(that.pn + 1).finally(() => {
					that.pn += 1;
					that.loading = false;
				});
			}
		});
	},
	onPageScroll(v) {
		if (v.scrollTop >= 200) {
			this.isShowGoTop = true;
		} else {
			this.isShowGoTop = false;
		}
	},
	methods: {
		boolLogin(callback) {
			let that = this;
			return new Promise((resolve, reject) => {
				that._plugins
					.boolLogin()
					.then(() => {
						callback && callback();
						resolve();
					})
					.catch(() => {
						uni.navigateTo({
							url: '../login/login'
						});
					});
			});
		},
		getMessageData(pn) {
			let that = this;
			return new Promise((resolve, reject) => {
				that.$store
					.dispatch('getMessageData', {
						pn: pn || 0
					})
					.then(res => {
						that.messages.data = pn > 0 ? that.messages.data.concat(res.data) : res.data;
						resolve();
					})
					.catch(err => {
						console.log(err);
						reject(err);
					});
			});
		},
		i18n(v) {
			return this.$t('index')[v];
		},
		parseType(v) {
			return this._plugins.returnMessageTypeData(v);
		},
		parseDate(v) {
			return this._plugins.dateFormate(v, 'yyyy-MM-dd hh:MM:ss');
		}
	}
};
</script>

<style lang="less">
.message {
	.message_tip {
		margin: 20rpx 20rpx;
		font-size: 28rpx;
	}
	.message_list {
		.message_list_item {
			margin: 40rpx 40rpx;
			font-size: 28rpx;
			.message_content {
				display: flex;
				.label {
					width: 100rpx;
					color: #999999;
				}
				custom-msg-to-component {
					flex: 1;
				}
			}
			.message_time {
				margin: 10rpx 20rpx 10rpx 100rpx;
				font-size: 20rpx;
				color: #999999;
			}
		}
	}
}
</style>
